<template>
  <div 
    class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
    v-if="visible"
    @click="handleOverlayClick"
  >
    <!-- 模态框容器 -->
    <div 
      class="bg-white rounded-lg shadow-xl w-full max-w-md mx-auto transform transition-all duration-300 scale-100"
      @click.stop
    >
      <!-- 模态框头部 -->
      <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
        <h3 class="text-lg font-medium text-gray-900">编辑用户</h3>
        <button 
          class="text-gray-400 hover:text-gray-500 focus:outline-none"
          @click="handleClose"
          aria-label="关闭"
        >
          <i class="fa fa-times"></i>
        </button>
      </div>
      
      <!-- 模态框内容 -->
      <div class="px-6 py-5">
        <form @submit.prevent="handleSubmit">
          <!-- 用户名 -->
          <div class="mb-4">
            <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
              用户名 <span class="text-red-500">*</span>
            </label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.name ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
              disabled="isSystemUser"
            >
            <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
            <p v-if="isSystemUser" class="mt-1 text-xs text-gray-500">
              <i class="fa fa-info-circle mr-1"></i>系统用户无法修改用户名
            </p>
          </div>
          
          <!-- 邮箱 -->
          <div class="mb-4">
            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">
              邮箱 <span class="text-red-500">*</span>
            </label>
            <input
              id="email"
              v-model="formData.email"
              type="email"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.email ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
            >
            <p v-if="errors.email" class="mt-1 text-sm text-red-600">{{ errors.email }}</p>
          </div>
          
          <!-- 角色 -->
          <div class="mb-4">
            <label for="roleId" class="block text-sm font-medium text-gray-700 mb-1">
              角色 <span class="text-red-500">*</span>
            </label>
            <select
              id="roleId"
              v-model="formData.roleId"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
              :class="errors.roleId ? 'border-red-500 focus:ring-red-500 focus:border-red-500' : ''"
              :disabled="isSystemUser && formData.isAdmin"
            >
              <option value="">请选择角色</option>
              <option 
                v-for="role in roles" 
                :key="role.id" 
                :value="role.id"
              >
                {{ role.name }}
              </option>
            </select>
            <p v-if="errors.roleId" class="mt-1 text-sm text-red-600">{{ errors.roleId }}</p>
            <p v-if="isSystemUser && formData.isAdmin" class="mt-1 text-xs text-gray-500">
              <i class="fa fa-info-circle mr-1"></i>系统管理员角色无法修改
            </p>
          </div>
          
          <!-- 全名 -->
          <div class="mb-4">
            <label for="fullName" class="block text-sm font-medium text-gray-700 mb-1">
              全名
            </label>
            <input
              id="fullName"
              v-model="formData.fullName"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
            >
          </div>
          
          <!-- 电话 -->
          <div class="mb-4">
            <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">
              联系电话
            </label>
            <input
              id="phone"
              v-model="formData.phone"
              type="tel"
              class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
            >
          </div>
          
          <!-- 状态 -->
          <div class="mb-4">
            <label class="flex items-center">
              <input
                v-model="formData.status"
                type="checkbox"
                true-value="active"
                false-value="inactive"
                class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded transition-colors"
              >
              <span class="ml-2 block text-sm text-gray-700">
                {{ formData.status === 'active' ? '账户已启用' : '账户已禁用' }}
              </span>
            </label>
          </div>
        </form>
      </div>
      
      <!-- 模态框底部 -->
      <div class="px-6 py-4 bg-gray-50 rounded-b-lg flex justify-end space-x-3">
        <button
          type="button"
          class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
          @click="handleClose"
          :disabled="loading"
        >
          取消
        </button>
        <button
          type="button"
          class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
          @click="handleSubmit"
          :disabled="loading"
        >
          <i v-if="loading" class="fa fa-spinner fa-spin mr-1"></i>
          保存更改
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed } from 'vue';
import { useValidator } from '@/composables/useValidator';

export default {
  props: {
    // 控制模态框显示/隐藏
    visible: {
      type: Boolean,
      default: false
    },
    // 用户数据
    user: {
      type: Object,
      default: () => ({
        id: null,
        username: '',
        email: '',
        roleId: '',
        fullName: '',
        phone: '',
        status: 'active',
        isAdmin: false,
        isSystemUser: false
      })
    },
    // 角色列表
    roles: {
      type: Array,
      default: () => []
    }
  },
  emits: ['close', 'save'],
  setup(props, { emit }) {
    // 表单数据
    const formData = ref({
      id: null,
      name: '',
      email: '',
      roleId: '',
      fullName: '',
      phone: '',
      status: 'active',
      isAdmin: false,
      isSystemUser: false
    });
    
    // 错误信息
    const errors = ref({});
    
    // 加载状态
    const loading = ref(false);
    
    // 系统用户判断
    const isSystemUser = computed(() => formData.value.isSystemUser);
    
    // 验证器 composable
    const { validateEmail, validateRequired } = useValidator();
    
    // 监听用户数据变化，同步到表单
    watch(() => props.user, (newUser) => {
      if (newUser) {
        formData.value = { ...newUser };
        // 重置错误
        errors.value = {};
      }
    }, { immediate: true, deep: true });
    
    // 表单验证
    const validateForm = () => {
      const newErrors = {};
      
      // 验证用户名
      if (!validateRequired(formData.value.name)) {
        newErrors.name = '请输入用户名';
      } else if (formData.value.name.length < 3 || formData.value.name.length > 20) {
        newErrors.name = '用户名长度必须在3-20个字符之间';
      }
      
      // 验证邮箱
      if (!validateRequired(formData.value.email)) {
        newErrors.email = '请输入邮箱地址';
      } else if (!validateEmail(formData.value.email)) {
        newErrors.email = '请输入有效的邮箱地址';
      }
      
      // 验证角色
      if (!validateRequired(formData.value.roleId)) {
        newErrors.roleId = '请选择角色';
      }
      
      // 更新错误信息
      errors.value = newErrors;
      
      // 返回是否验证通过
      return Object.keys(newErrors).length === 0;
    };
    
    // 处理提交
    const handleSubmit = async () => {
      // 表单验证
      if (!validateForm()) {
        // 自动聚焦到第一个错误字段
        const firstErrorField = Object.keys(errors.value)[0];
        document.getElementById(firstErrorField)?.focus();
        return;
      }
      
      try {
        loading.value = true;
        // 触发保存事件，将表单数据传递给父组件
        emit('save', { ...formData.value });
      } catch (error) {
        console.error('提交表单失败:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 处理关闭
    const handleClose = () => {
      emit('close');
    };
    
    // 点击遮罩层关闭
    const handleOverlayClick = () => {
      handleClose();
    };
    
    return {
      formData,
      errors,
      loading,
      isSystemUser,
      handleSubmit,
      handleClose,
      handleOverlayClick
    };
  }
};
</script>

<style scoped>
/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.fixed.inset-0 {
  animation: fadeIn 0.2s ease-out forwards;
}

.bg-white.rounded-lg {
  animation: scaleIn 0.2s ease-out forwards;
}

/* 禁用状态样式 */
input:disabled, select:disabled {
  background-color: #f9fafb;
  cursor: not-allowed;
  opacity: 0.7;
}
</style>
    